package com.universest.swordholder.viewmodel.passage_editor

import android.util.Log
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.universest.swordholder.model.config.ConfigItem
import com.universest.swordholder.model.user.UserManager
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.map

class PassageEditorConfigManager() {

    private var _configItems = MutableStateFlow<List<ConfigItem>>(listOf(
        ConfigItem(
            key = "showActionBarText",
            type = "checkbox",
            name = "显示操作栏文字",
            defaultValue = "true",
            description = "可以配置是否显示文本操作栏中按钮下方小文字。"
        ),
        ConfigItem(
            key = "actionBarAlwaysShow",
            type = "checkbox",
            name = "操作栏常驻",
            defaultValue = "false",
            description = "可以配置文本操作栏是否一直显示，如果关闭，文本操作栏将只在软键盘弹出时显示。"
        ),
        ConfigItem(
            key = "showCharCount",
            type = "checkbox",
            name = "开启字数统计",
            defaultValue = "true",
            description = "可以控制右上角的字数统计浮窗是否显示。"
        ),
        ConfigItem(
            key = "autoIndent",
            type = "checkbox",
            name = "自动缩进",
            defaultValue = "true",
            description = "选择此项后，换行时，将自动缩进，缩进数量为编辑前所在行的缩进数量。"
        ),
        ConfigItem()
    ))

    val configItem = _configItems.asStateFlow()

    fun getUserConfig(key: String, defaultValue: String): Flow<String> {
        return UserManager.Companion.instance.getUserConfigManager()
            .getConfig(key,defaultValue)
            .map { it ?: defaultValue }
    }

    fun getUserConfig(configItem: ConfigItem): Flow<String> {
        return UserManager.Companion.instance.getUserConfigManager()
            .getConfig(configItem.key,configItem.defaultValue)
            .map { it ?: configItem.defaultValue }
    }

    suspend fun setUserConfig(configItem: ConfigItem, value: String) {
        try {
            UserManager.Companion.instance.getUserConfigManager()
                .saveConfig(configItem.key, value)
        }catch (e: Throwable){
            Log.e("PassageEditorViewModel", "setUserConfig error: $e")
        }
    }
}